/**
* Class Name: iFulfillMoveBackController
* Author: Accenture       Date: 13-Jun-2011
* Requirement/Project Name: iFULFILL
* Requirement/Project Description: Allows reps to track the backword movement of fullfillment item when rejected/ sent for rework
* Bhumika Udani         v2.1    Improvised based on peer review
* Sapna Jaamdar         v2.2    Refactored. 
* Bhumika Udani         v2.3    Re-assigning to Assignment Group included
* Bhumika Udani         v2.4    Removed assigning fitem owner id to task instruction as Sayeed's email
**/


public with sharing class iFulfillMoveBackController {

    Fullfilment_Item__c fItem = new Fullfilment_Item__c();
    list<Fulfillment_Step_History__c> taskHistoryList;
    list<Wokflow_Steps__c> skippedTaskAsngList;
    list<Workflow_Stage__c> backFunction= new list<Workflow_Stage__c>();
    list<Wokflow_Steps__c> currentfunctionTaskList = new list<Wokflow_Steps__c>();
    list<Assignment_Group_Queues__c> fetchedQueueIds = new list<Assignment_Group_Queues__c>();
    
    Id bkTaskId; 
    
    public boolean exceptionFlag{get;set;}
    public boolean assignUserAsOwner{get;set;}         
    public string selStage{get;set;}
    public string selstep{get;set;}
    public string ReasonDetails{get;set;}
    public String sReason{get;set;} 
    public string ftype{get;set;}    
    public string fI_type{get;set;}
    public string description{get;set;}            
    public string Category{get;set;}    
    public List<SelectOption> PrevTask{get;set;}  
    public List<SelectOption> PrevFunc{get;set;}
    public List<SelectOption> preTaskList{get;set;}
    public string AssignmentGroup{get;set;}

                
    /**  Constructor **/
    public iFulfillMoveBackController (ApexPages.StandardController controller) {
        fItem = (Fullfilment_Item__c)controller.getRecord();
        fI_type = ApexPages.currentPage().getParameters().get('type'); 
        exceptionFlag = true;
    }
    
    public pagereference dummy(){
        return null;    
    }
    
     /** Load all the previous functions available in the Workflow definition. ***/
     /** Method called on page load***/
     
     public void Previousfunction(){             
       if(fItem.Current_Stage__c !=null){                  
           if(fItem.Current_Step__r.Sequence__c == 1) 
           
              /** check to find out if current function should be displayed or not**/
               backFunction = [select id,Name from Workflow_Stage__c where Workflow_Code__c=:fItem.Workflow_Code__c and Sequence__c < :fItem.Current_Stage__r.Sequence__c order by Sequence__c asc];                       
           else
               backFunction = [select id,Name from Workflow_Stage__c where Workflow_Code__c=:fItem.Workflow_Code__c and Sequence__c <= :fItem.Current_Stage__r.Sequence__c order by Sequence__c asc];                       
           PrevFunc = new List<SelectOption>();
           if(backFunction.size()>0){  
               selStage = backFunction[0].id; 
               
               /*** default function to be displayed  **/
               for(Workflow_Stage__c ws : backFunction){
                        PrevFunc.add(new SelectOption(ws.id,ws.Name));         
                }                   
                 previousTask();
                 selStep = PrevTask[0].getvalue(); /**default task to be displayed**/
                 previousAssignGroup();        
           }         
         }                   
      }
               
        /**Create instruction record **/
        
        public void newInstructionRecord(){                      
            
            system.debug('Creating Instruction record');                  
            
            /** Querying corresponding object ids to fetch name information ***/
            
            Workflow_Stage__c stg = [select id, name from Workflow_Stage__c where id =: selstage];
            Wokflow_Steps__c stp =  [select id, name,Dashboard_Function__c from Wokflow_Steps__c where id=:selstep];                   
        
            /** Update the owner based on history record either user or Assignment group. **/
            /** Do this before creating Task Instruction to assign correct owner to task instruction  **/
              
                if(assignUserAsOwner) {
                    fItem.ownerid =taskHistoryList[0].ownerid ;}
             
                else if(!assignUserAsOwner){
                        fItem.ownerid = fetchedQueueIds[0].QueueId__c;                
                }        
                
            /*** Create new task instruction record to track every stage and function change.   **/
            
            Task_Instruction__c tr = new Task_Instruction__c();                            
             tr.Item_ID__c=fitem.id;
             tr.Description__c=description;          
             tr.Type__c=fI_type;
             if(stg.name!=null){
                 tr.Current_Function__c=stg.name;
              }         
             if(stp.name!=null){
                 tr.Current_Task__c= stp.name;
             }                           
             tr.Previous_Next_Function__c=fItem.Current_Function_Name__c;                 
             tr.Previous_Next_Task__c=fItem.Current_Task_Name__c;  
             /**commenting below line as per Sayeed's email,owner can be default **/
             /** tr.ownerid = fItem.ownerid ;   **/
            try{
                insert tr;       
            }catch(dmlexception e){GeneralConstants.mailAnyExceptionToMe('iFulfillMoveBackController', 'newInstructionRecord' + 'Insert Task Instructio failed', e);}  
          
           /** Update the fulfillment item**/
           
           fItem.Previous_Dashboard__c = fItem.Current_Step__r.Dashboard_Function__c;        
           fItem.Previous_Task__c = fItem.Current_Task_Name__c;         
           fItem.Previous_Function__c = fItem.Current_Function_Name__c;
           fItem.Current_Step__c=selstep;   
           fItem.Current_Stage__c= selStage;
           if(fI_type == IfullfillTextConstant.FI_REWORK ){
               fItem.In_Rework_Reject__c = IfullfillTextConstant.FI_REWORK;
           }
           else{
               fItem.In_Rework_Reject__c = IfullfillTextConstant.FI_REJECT;
           }
           fItem.Current_Stage_Start_Date__c = system.now();        
           fItem.Current_Step_Start_Date__c = system.now();
           try{update fItem;}
           catch(dmlexception e)
           {    
                /*** Set the exception flag to false incase  exception occurs**/
                exceptionFlag = false;
                IfullfillTextConstant.parseExceptionMsg(e,'iFulfillMoveBackController','newInstructionRecord');
           }     
       }

        /** dynamically fetches the tasks for the selected function      **/
        public pagereference previousTask(){            
            list<Wokflow_Steps__c> backTask = new list<Wokflow_Steps__c>(); 
            PrevTask  = new List<SelectOption>(); 
            if((fItem.Current_Step__r.Sequence__c == 1 && fItem.Current_Stage__c == selStage) || fItem.Current_Stage__c != selStage)              
                backTask=[select id, name,Dashboard_Function__c, Sequence__c,Step__c from Wokflow_Steps__c where Wokflow_Stage_Name__c =:selStage];  // get tasks of previous functions only
            else  
                backTask=[select id, name,Dashboard_Function__c, Sequence__c,Step__c from Wokflow_Steps__c where Wokflow_Stage_Name__c =:selStage and sequence__c < :fItem.Current_Step__r.Sequence__c];  //get tasks of previous and current function           

            for(Wokflow_Steps__c wst : backTask){
               PrevTask.add(new SelectOption(wst.id,wst.Name));         
               }      
            selStep = PrevTask[0].getvalue();//default task to be displayed         
            previousAssignGroup();                
            return null;            
        }
        
       /** gets the user who last worked on the FI for the selected function/task from the history table **/
       
        public pagereference previousAssignGroup(){                   
            list<Wokflow_Steps__c> backTask;              
            taskHistoryList = new list<Fulfillment_Step_History__c>();
            skippedTaskAsngList = new list<Wokflow_Steps__c>();
            list<User> activeUserList = new list<User>();
            Id ActiveUser; 


            backTask=[select name from Wokflow_Steps__c where id =:selStep];      
            
            if (backTask.size()>0)       taskHistoryList = [select ownerid,owner__c, createdBy.id, createdBy.Name from Fulfillment_Step_History__c where Step__c =: backTask[0].name and Fullfilment_Item__c =: fItem.id and Type__c != 'Skip' and Status__c = 'In Progress' order by Task_End_Date__c DESC limit 1];            
              system.debug(taskHistoryList);
            
            if (taskHistoryList.size()>0) activeUserList = [select id from user where id =:taskHistoryList[0].ownerid  and isActive =true];
              system.debug('This user is active '+activeUserList);
                    
            if(taskHistoryList.size()>0 && activeUserList.size()>0){           
                        /** Assign the item to user only if user is Active**/
                        
                      AssignmentGroup = taskHistoryList[0].owner__c;
                      assignUserAsOwner = true;
              }
            
            else{
                 
                 /*** Assign the item to Assignment group belonging the Task ***/
                 
                 system.debug('I am in here');
                 skippedTaskAsngList = [select Default_Group__c,Default_Group__r.name from Wokflow_Steps__c where id =: selStep];
                 
                 if(skippedTaskAsngList.size()>0){  
                    
                    AssignmentGroup = skippedTaskAsngList[0].Default_Group__r.name;

                    /** fetch corresponding Queue id associated with AG Queues***/
                    fetchedQueueIds  = [select QueueId__c from Assignment_Group_Queues__c where Assignment_Group_Name__c =: skippedTaskAsngList[0].Default_Group__c]; 
                    
                    system.debug('This is IT '+AssignmentGroup);
                    system.debug(fetchedQueueIds);
                        if(fetchedQueueIds.size()>0){
                            assignUserAsOwner=false;
                            }
                   }
            }
            return null;       
        }   
}